package edu.arizona.eller.mis.liferoulette;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class sms_send extends Activity implements OnClickListener{
    Button sendButton, browseButton;
    EditText phoneTextField;
    EditText msgTextField;
	String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";
    String name = null;
    String vicinity = null;
    BroadcastReceiver b1, b2;

	    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sms_send);  
        
        Intent i = getIntent();
        if(i.getStringExtra("name").isEmpty())
        	name = "";
        else
        	 name = i.getStringExtra("name");
        
        if(i.getStringExtra("vicinity").isEmpty())
        	vicinity = "";
        else
        	vicinity = i.getStringExtra("vicinity");
        
        msgTextField = (EditText) findViewById(R.id.msgTextField);
        msgTextField.setText("On my way to " + name + " : " + vicinity );
        
        sendButton = (Button) findViewById(R.id.sendButton);
        
        browseButton = (Button) findViewById(R.id.browseButton);
        browseButton.setOnClickListener(this);
        
        phoneTextField = (EditText) findViewById(R.id.phoneTextField);
       
    }

    // callback for send button
    public void send(View v)
    {
    	try{
	    	unregisterReceiver(b1);
	    	unregisterReceiver(b2);
    	}catch(Exception e){
            //Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    	}
    	
        String phoneNumber = phoneTextField.getText().toString();
        String msg = msgTextField.getText().toString();  
        //remove hyphens before sending
        phoneNumber = phoneNumber.replace("-", "");
        //handle multiple addresses separated by semicolon
        String delims = ";";
        String[] numberArray = phoneNumber.split(delims);
        
        //send messages
        if (phoneNumber.length()>0 && msg.length()>0){
      
             PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                 new Intent(SENT), 0);
      
             PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                 new Intent(DELIVERED), 0);
           
             
             //check sms code when message is sent
             registerReceiver(b1 = new BroadcastReceiver(){
                 @Override
                 public void onReceive(Context arg0, Intent arg1) {
                     switch (getResultCode())
                     {
                         case Activity.RESULT_OK:
                             Toast.makeText(getBaseContext(), "SMS sent", 
                                     Toast.LENGTH_SHORT).show();
                             break;
                         case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                             Toast.makeText(getBaseContext(), "Generic failure", 
                                     Toast.LENGTH_SHORT).show();
                             break;
                         case SmsManager.RESULT_ERROR_NO_SERVICE:
                             Toast.makeText(getBaseContext(), "No service", 
                                     Toast.LENGTH_SHORT).show();
                             break;
                         case SmsManager.RESULT_ERROR_NULL_PDU:
                             Toast.makeText(getBaseContext(), "Null PDU", 
                                     Toast.LENGTH_SHORT).show();
                             break;
                         case SmsManager.RESULT_ERROR_RADIO_OFF:
                             Toast.makeText(getBaseContext(), "Radio off", 
                                     Toast.LENGTH_SHORT).show();
                             break;
                     }
                 }
             }, new IntentFilter(SENT));
      
            //check result code when the message has been delivered
			registerReceiver(b2 = new BroadcastReceiver(){
                 @Override
                 public void onReceive(Context arg0, Intent arg1) {
                     switch (getResultCode())
                     {
                         case Activity.RESULT_OK:
                             Toast.makeText(getBaseContext(), "SMS delivered", 
                                     Toast.LENGTH_SHORT).show();
                             break;
                         case Activity.RESULT_CANCELED:
                             Toast.makeText(getBaseContext(), "SMS not delivered", 
                                     Toast.LENGTH_SHORT).show();
                             break;                        
                     }
                 }
             }, new IntentFilter(DELIVERED));        
             
             for (int i = 0; i < numberArray.length; i++){	
            	//System.out.println(numberArray[i]);
 	            SmsManager sms = SmsManager.getDefault();
 	            sms.sendTextMessage(numberArray[i], null, msg, sentPI, deliveredPI);

 	         }     

        }else{
	        Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
	    }
	}
	    
    public void onClick(View v) {
		
		if(v == browseButton){
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);            
            startActivityForResult(intent, 1); 
			
		}
	}
	
    @Override
    public void onPause(){
    	super.onPause();
    	try{
	    	unregisterReceiver(b1);
	    	unregisterReceiver(b2);
    	}catch(Exception e){
            //Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    	}
    }
    
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            Uri uri = data.getData();

            if (uri != null) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, new String[]{ 
                                ContactsContract.CommonDataKinds.Phone.NUMBER,  
                                ContactsContract.CommonDataKinds.Phone.TYPE },
                            null, null, null);

                    if (c != null && c.moveToFirst()) {
                        String number = c.getString(0);
                        int type = c.getInt(1);
                        setSelectedNumber(type, number);
                    }
                    
                } finally {
                    if (c != null)
                        c.close();
                    
                }
            }
        }
    }
	

    public void setSelectedNumber(int type, String number) {
        Toast.makeText(this, "added contact: " + type + ": " + number, Toast.LENGTH_LONG).show();
        if(phoneTextField.getText().toString().equals(""))
        	phoneTextField.append(type + number);
        else
        	phoneTextField.append(";" + type + number);   
    }
	
	
	    public boolean onCreateOptionsMenu(Menu menu) {
		    MenuInflater inflater = getMenuInflater();
		    inflater.inflate(R.menu.activity_menu, menu);
		    return true;
		}
		
		public boolean onOptionsItemSelected(MenuItem item) {
		    switch (item.getItemId()) {
		        case R.id.settingsItem:     
		        	startActivity(new Intent(this, UserPreferenceAcvitity.class));
		            break;
		        case R.id.historyItem:     
		        	startActivity(new Intent(this, HistoryActivity.class));
		            break;
		        case R.id.homeItem:     
		        	startActivity(new Intent(this, main.class));
		            break;
		    }
		    return true;
		}
}
